import 'dart:convert';

import 'package:audioplayers/audioplayers.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/ui/room/LiveRoomPage.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/gift_list_request.dart';
import 'package:elephant_fish/http/request/give_gift_request.dart';
import 'package:elephant_fish/http/request/user_info_request.dart';
import 'package:elephant_fish/model/gift_entity.dart';
import 'package:elephant_fish/model/user_info_entity.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:elephant_fish/widget/one_gift.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'login_page.dart';

class OneGiftPage extends StatefulWidget {
  final int categoryName;
  final int roomId;
  final bool isShield;
  final int userId;
  const OneGiftPage({Key key, this.categoryName, this.roomId, this.isShield, this.userId}) : super(key: key);

  @override
  _OneGiftPageState createState() => _OneGiftPageState();
}

class _OneGiftPageState extends State<OneGiftPage> {
  List<GiftEntity> gifts = [];
  int pageIndex = 1;
  UserInfoEntity userInfoEntity;
  bool _loading = false;
  TextEditingController inputController = new TextEditingController();
  TextEditingController numController = new TextEditingController(text: '1');
  final inputFocusNode = FocusNode();
  ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    super.initState();
    getInitData();
    _loadData();
  }


  safeSetState(callBack) {
    setState(() {
      if (mounted) {
        callBack();
      }
    });
  }



  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Color(0x660c0c0c),
      body:Column(
        children: [
           Expanded(
              child:  StaggeredGridView.countBuilder(
                  shrinkWrap: true,
                  controller: _scrollController,
                  physics: const AlwaysScrollableScrollPhysics(),
                  padding: EdgeInsets.only(left: 3,right: 3,top: 3),
                  crossAxisCount: 4,
                  crossAxisSpacing: 4,
                  itemCount: gifts.length,
                  itemBuilder: (BuildContext context, int index) {
                    //有banner时第一个item位置显示banner
                    return OneGift(giftEntity: gifts[index],);
                  },staggeredTileBuilder: (int index) {
                return StaggeredTile.fit(1);
              }) ,
            ),
          Container(
            height: SizeUtil.px(74),
            child: Stack(
              children: [
                Align(
                  alignment: Alignment.centerLeft,
                  child: Padding(
                    padding: EdgeInsets.only(left: SizeUtil.px(25)),
                    child: Text(
                      '金币',style: TextStyle(fontSize: SizeUtil.px(28),color: Color(0xfffbb905)),
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.centerLeft,
                  child: Padding(
                    padding: EdgeInsets.only(left: SizeUtil.px(91)),
                    child: Text(
                      userInfoEntity == null ? '0' :userInfoEntity.currentGold,style: TextStyle(fontSize: SizeUtil.px(28),color: Color(0xfffbb905)),
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.centerLeft,
                  child: Padding(
                    padding: EdgeInsets.only(left: SizeUtil.px(222)),
                    child: Image.asset(
                      'assets/images/gift_money.png',width: SizeUtil.px(29.48),height: SizeUtil.px(33.69),),
                  ),
                ),
                Align(
                  alignment: Alignment.centerLeft,
                  child: Padding(
                    padding: EdgeInsets.only(left: SizeUtil.px(267)),
                    child: Text(
                      '充值',style: TextStyle(fontSize: SizeUtil.px(28),color: Color(0xfffbb905)),
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: Padding(
                    padding: EdgeInsets.only(right: SizeUtil.px(20)),
                    child: Container(
                    width: 100,
                      child: TextField(
                        keyboardType: TextInputType.number,
                        controller: numController,
                        decoration: InputDecoration(
                          border: InputBorder.none,
                        ),
                        style: TextStyle(
                          fontSize: 16,height: 2,color: Colors.white
                        ),
                      ),
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: Padding(
                    padding: EdgeInsets.only(right: SizeUtil.px(25)),
                    child: InkWell(
                      onTap: (){
                        sendGift();
                      },
                      child: Container(
                        width: SizeUtil.px(105),
                        height: SizeUtil.px(46),
                        decoration: BoxDecoration(
                          color: Color(0xffe62d6c),
                          borderRadius: BorderRadius.all(Radius.circular(SizeUtil.px(4))),

                        ),
                        child: Center(
                          child: Text('发送',style: TextStyle(fontSize: SizeUtil.px(23),color: Color(0xffe1e1e1)),),
                        ),
                      ),
                    )
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  void _loadData({loadMore = false})async {
    _loading = true;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = GiftListRequest();
    request.add('classify_id', widget.categoryName).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(arguments: {'loginCode':'-1'},);
        },
      ));
    }else if(result['code'] == 0) {
      List<Map<String,dynamic>> listMap = new List<Map<String, dynamic>>.from(result['data']['data']);
      List<GiftEntity> gift = [];
      for (int i = 0; i < listMap.length; i ++) {
        gift.add(GiftEntity.fromJson(listMap[i])) ;
      }
      setState(() {
        gifts = gift;
      });
    }
  }


  Future<void> sendGift() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String gift = prefs.getString('GIFTINFO');
    String number = numController.text;
    int num = int.parse(number);
    if(gift == ''){
      TxUtils.showToast('请选择礼物', context);
    }else if(num <=0){
      TxUtils.showToast('礼物数量需为正数', context);
     }else{
      GiftEntity giftEntity = GiftEntity.fromJson(jsonDecode(gift));
      String appToken = prefs.getString('app-token');
      BaseRequest request = GiveGiftRequest();
      request.add('room_id',widget.roomId).add('receive_user_id', widget.userId).add('type', 2).add('gift_id', giftEntity.id).add('count', num).addHeader('usertoken', appToken);
      var result = await HiNet.getInstance().fire(request);
      if (result['code'] == -1) {
        TxUtils.showErrorToast('登录失效，请重新登录', context);
        Navigator.pop(context);
        Navigator.of(context).push(MaterialPageRoute(
          builder: (context) {
            return LoginPage(arguments: {'loginCode':'-1'},);
          },
        ));
      }else if(result['code'] == 0) {
        TxUtils.showToast(result['data'], context);
        trtcLiveCloud.sendRoomCustomMsg('gift', gift);
        if(!widget.isShield){
          play();
        }
        addGiftMessage(gift);
        getInitData();
      }

    }
  }

  ///赠送礼物播放声音
  play() async {
    AudioPlayer audioPlayer = AudioPlayer();
    int result = await audioPlayer.play('http://119.28.131.94:82/uploads/Music/1.mp3');
    if (result == 1) {
      // success
      print('play success');
    } else {
      print('play failed');
    }
  }

  addGiftMessage(String giftInfo){
    safeSetState(() {
      giftList.add(giftInfo);
      if(giftList.length > 3){
        giftList.removeAt(0);
      }
    });
  }

  Future<void> getInitData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = UserInfoRequest();
    request.add('type', 2).addHeader('usertoken',appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(arguments: {'loginCode':'-1'},);
        },
      ));
    }
    setState(() {
      userInfoEntity = UserInfoEntity.fromJson(new Map<String, dynamic>.from(result['data']));
      prefs.setString('USERINFO', jsonEncode(userInfoEntity));
      print(userInfoEntity);
    });

  }
}
